const notificationApi = require('../../../api/notification')

Page({
  data: { headerHeight: 0, list: [], loading: false },
  onLoad() { this.loadList() },
  onHeaderReady(e) { const { totalHeight } = e.detail || {}; this.setData({ headerHeight: totalHeight || 0 }) },
  async loadList(){
    this.setData({ loading: true })
    try {
      const res = await notificationApi.list({ userType: 'parent' })
      if (res && res.success) {
        const list = (res.data || []).map(it => ({
          ...it,
          timeText: this.formatTime(it.createTime)
        }))
        this.setData({ list })
      }
    } finally { this.setData({ loading: false }) }
  },
  formatTime(ts){
    try{ const d = new Date(ts.replace(/-/g,'/')); const diff = (Date.now() - d.getTime())/1000;
      if (diff < 60) return '刚刚'; if (diff < 3600) return `${Math.floor(diff/60)}分钟前`;
      if (diff < 86400) return `${Math.floor(diff/3600)}小时前`; const mm = String(d.getMonth()+1).padStart(2,'0'), dd = String(d.getDate()).padStart(2,'0');
      return `${mm}-${dd}` }catch(e){ return ts || '' }
  },
  async markRead(e){
    const id = e.currentTarget.dataset.id
    await notificationApi.markRead({ id, userType: 'parent' })
    this.loadList()
  },
  async markAll(){
    await notificationApi.markAll({ userType: 'parent' })
    this.loadList()
  }
})

